package com.example.wj.controller;

import com.example.wj.service.UserService;
import com.example.wj.pojo.Result;
import com.example.wj.pojo.User;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class RegisterController {
    @Autowired
    UserService userService;

    @CrossOrigin

    @RequestMapping(value = "api/register")
    @ResponseBody
    public Result save(@RequestBody User user) {
        Result result = null;
        User user1 = userService.seachUser(user.getUsername());
        System.out.println(user1);
        if ("".equals(user.getUsername()) && "".equals(user.getPassword())) {
            result = new Result(403);
        } else if ("".equals(user.getUsername())) {
            result = new Result(401);
        } else if ("".equals(user.getPassword())) {
            result = new Result(402);
        } else if (user1 != null) {
            result = new Result(404);
        } else {
            //生成盐
            String salt = new SecureRandomNumberGenerator().nextBytes().toString();
            //生成简单hash码
            String encodedPassword = new SimpleHash("md5", user.getPassword(), salt, 2).toString();
            user.setSalt(salt);
            user.setPassword(encodedPassword);
            System.out.println("密码" + salt + encodedPassword);
            //得到hash密码

            int save = userService.save(user);
            if (save == 1) {
                result = new Result(200);
                System.out.println("result="+result);

            } else {
                result = new Result(500);
            }
        }
        return result;
    }
}
